<?php
/**
 * Created by PhpStorm.
 * User:tsingStar
 * Date: 2019/8/2
 * Time: 17:39
 */

namespace app\home\controller;

use app\common\model\Region;
use app\common\model\User as umodel;
use think\Db;
use think\Url;

class User extends Common
{

    protected function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 用户中心
     */
    public function index()
    {
        $this->templateTitle("会员中心");
        $uid = session("user_id");
        if (empty($uid)) {
            session('tips', '请先登录');
            $this->redirect("Index/login");
        }
        $userinfo = userallinfo($uid);
        if (empty($userinfo)) {
            session("user_id", '');
            $this->redirect("Index/login");
        }
        $userinfo['userlevel'] = umodel::thatlevel($userinfo['levelid']);
        /*读取会员的总资产*/
        //先读取我买的订单，还没有匹配的，并且计算出这些订单分别的收益

        $userinfo['property'] = user_pro_money($uid);
        //计算总收入
        $profits = getProfits($uid);
        $userinfo['profits'] = $profits;
        $this->assign('userinfo', $userinfo);
        //抢购订单
        $readdata['paystatus'] = 0;
        $readdata['peiduiuid'] = $uid;//我买的单子
        $buynoread = Db::name(config('db_order_table'))->where($readdata)->count();
        $countnum['buynoread'] = intval($buynoread);
        //转让订单
        $saledata['isread'] = 1;
        $saledata['xs'] = 2;
        $saledata['buyuid'] = $uid;//我卖的订单
        $now_date_str = date('Y-m-d');
        $saledata['cansaletime'] = array('<=', strtotime($now_date_str));
        $salenoread = Db::name(config('db_order_table'))->where($saledata)->count();
        $countnum['salenoread'] = intval($salenoread);
        $this->assign('countnum', $countnum);
        return $this->fetch("index");
    }

    /*
     * 邀请好友
     * */
    public function invites()
    {
        //查看收款方式是否已经认证
        $uid = session("user_id");
        if (empty($uid)) {
            session('tips', '请先登录');
            $this->redirect("Index/login");
        }
        $count = \app\common\model\User::getChargeCount($uid);
        if (!$count >= 2) {

            $this->assign('tips', "请绑定两个以上（包含两个）的收款码");
            $this->assign("redirect_url", \url('User/add_bank'));
            return $this->fetch('alert_window');
        }
        //查看是否已经实名认证
        $userinfo = userallinfo($uid);
        $is_verify = 0;
        if ($userinfo['selfcard'] <> '' && $userinfo['realname'] <> '') {
            $is_verify = 1;
        }
        if (!$is_verify) {
            $this->assign('tips', "请先去实名认证");
            $this->assign("redirect_url", \url('User/certification'));
            return $this->fetch('alert_window');
        }
        return $this->fetch("invites");
    }

    /*
     * 个人中心邀请好友生成二维码
     */
    public function erimg()
    {
        require_once(EXTEND_PATH . '/phpqrcode/phpqrcode.php');
        $object = new \QRcode();
        $uid = session("user_id");
        $userinfo = userallinfo($uid);
        $url = Url::build('Index/register', 'codes=' . base64_encode($userinfo['invite_code']), 'html', true);
        $level = 5;
        $size = 10;
        $errorCorrectionLevel = intval($level);//容错级别
        $matrixPointSize = intval($size);//生成图片大小
        return $object->png($url, false, $errorCorrectionLevel, $matrixPointSize, 2);
        exit();
    }

    /*
     * 我的团队
     * */
    public function myteam()
    {
        $this->templateTitle("团队统计");
        /*团队累计推广收益*/
        $uid = session("user_id");
        if (empty($uid)) {
            session('tips', '登录过期，请重新登录');
            $this->redirect("Index/login");
        }
        $userinfo = userallinfo($uid);
        $this->assign('userinfo', $userinfo);
        $teamsnum = Db::name('user')->where("recommend like '%," . $uid . ",%' and is_active=1")->field('id')->count();
        $teams_active = Db::name('user')->where("recommend like '%," . $uid . ",%' and user_status=1 and is_active=1")->field('id')->count();
        $recommend_num = \db('user')->where('pid', $uid)->where('is_active', 1)->count();
        $active_recommend_num = \db('user')->where('pid', $uid)->where('user_status', 1)->where('is_active', 1)->count();
        $this->assign('recommend_num', $recommend_num);
        $this->assign('active_recommend_num', $active_recommend_num);
        $this->assign('teamsnum', $teamsnum);
        $this->assign('teams_active', $teams_active);
        return $this->fetch("myteam");
    }

    /*
     *
     * 团队列表
     *
     * */
    public function teamlist()
    {
        $this->templateTitle("团队列表");
        $uid = session("user_id");
        if (empty($uid)) {
            session('tips', '登录过期，请重新登录');
            $this->redirect("Index/login");
        }
        $userinfo = userallinfo($uid);
        $next_rand = ($userinfo['rank'] + 2);

        $pagenum = 6;

        if (empty($_GET['types']) || $_GET['types'] == 1) {
            $type = 1;
            $userlist = Db::name('user')->where("pid = '" . $uid . "' ")->field('id,username,pid,user_status,is_active')->limit($pagenum)->select();
        }
        if (input('types') == 2) {
            $type = 2;
            $userlist = Db::name('user')->where("recommend like '%," . $uid . ",%' and rank='" . $next_rand . "'")->field('id,username,pid,user_status,is_active')->limit($pagenum)->select();
        }
        $this->assign('types', $type);

        if (!empty($userlist)) {
            foreach ($userlist as $k => $v) {
                $userlist[$k]['nextcount'] = Db::name('user')->where("pid = '" . $v['id'] . "' ")->count();
            }
        }
        $this->assign('userlist', $userlist);
        //查询我的团队激活的总人数
        $teamcount = $userinfo['teamcount'];
        $this->assign('teamcount', $teamcount);
        //查询团队总人数
        $totalteam = \db('user')->where("recommend", 'like', '%,' . $uid . ',%')->count();
        $this->assign('totalteam', $totalteam);
        return $this->fetch("teamlist");
    }

    /*
     * 团队无限极下拉加载二级会员
     * */
    public function ajaxmoreteams()
    {

        $page = $_POST['page'];/*当前是第几页*/
        $page_num = 5;/*每次读取5条*/
        $limit_first = ($page - 1) * $page_num;
        $limit_end = $page_num;
        $uid = session("user_id");
        $userinfo = userallinfo($uid);

        $next_rand = ($userinfo['rank'] + 2);
        /*1 一级会员  2二级会员*/
        if (empty($_POST['types']) || $_POST['types'] == 1) {
            $type = 1;
            $userlist = Db::name('user')->where("pid = '" . $uid . "' ")->field('id,username,pid,user_status,is_active,selfphone,regtime create_time')->limit($limit_first, $limit_end)->select();
        }
        if ($_POST['types'] == 2) {
            $type = 2;
            $userlist = Db::name('user')->where("recommend like '%," . $uid . ",%' and rank='" . $next_rand . "'")->field('id,username,pid,user_status,is_active,selfphone,regtime create_time')->limit($limit_first, $limit_end)->select();
        }
        if (!empty($userlist)) {
            foreach ($userlist as &$v) {
                $v['nextcount'] = Db::name('user')->where("pid = '" . $v['id'] . "' ")->count();
//                $v['create_time'] = show_datetime($v['create_time']);
            }
        }
        echo json_encode($userlist);
        exit();
    }

    /*
     * 实名认证
     * */
    public function certification()
    {

        $this->templateTitle("实名认证");
        $uid = session("user_id");
        if (empty($uid)) {
            session('tips', '登录过期，请重新登录');
            $this->redirect("Index/login");
        }
        $userinfo = userallinfo($uid);
        $is_verify = 0;
        if ($userinfo['selfcard'] <> '' && $userinfo['realname'] <> '' && $userinfo['mustman'] <> '') {
            $is_verify = 1;
        } else {
            /*判断是否ajax传过来的*/
            if (!empty($_POST)) {
                $jsonstr = umodel::verify_name($_POST);
                echo $jsonstr;
                exit;
            }
        }
        if ($is_verify == 1) {
            $this->assign('msg', '恭喜，实名认证已通过');
            return $this->fetch("certificationok");
        } else {
            //查询是否已经提交过，并显示提交之后审核的状态，最近一次的提交记录
            $res = \db("card_apply")->where("user_id", $uid)->where("is_trash", 0)->order("id desc")->find();
            if (!empty($res)) {
                if ($res['status'] == 0) {
                    //待审核
                    $msg = "实名认证申请正在审核";
                } elseif ($res['status'] == 1) {
                    //审核通过
                    $msg = '恭喜，实名认证已通过';
                } else {
                    //拒绝
                    $msg = "实名认证未通过，原因：" . $res['remark'];
                }
                $this->assign('msg', $msg);
                $this->assign('status', $res['status']);
                return $this->fetch("certificationok");
            }
            $this->assign('userinfo', $userinfo);
            return $this->fetch("certification");
        }
    }

    /**
     * 重新上传实名认证
     */
    public function resub()
    {
        //更新拒绝的申请记录
        \db("card_apply")->where("user_id", session('user_id'))->where("status", 2)->update(["is_trash" => 1]);
        $this->redirect('User/certification');
    }

    /**
     * 检验是否已经认证
     */
    public function checkCertify()
    {
        $uid = session("user_id");
        if (empty($uid)) {
            session('tips', '登录过期，请重新登录');
            $this->redirect("Index/login");
        }
        $count = \app\common\model\User::getChargeCount($uid);
        if ($count >= 2) {
            $this->redirect("User/certification");
        } else {
            $this->assign('tips', "请绑定两个以上（包含两个）的收款码");
            $this->assign("redirect_url", \url('Paytype/new_add'));
            return $this->fetch("alert_window");
        }
    }

    /*
     * 我要申诉
     * */
    public function appeal()
    {
        $this->templateTitle("我要申诉");
        $back_url = input('u');
        if (empty($back_url)) {
            $back_url = Url::build('User/index', '', 'html', true);
        } else {
            $back_url = base64_decode($back_url);
        }
        $this->assign('back_url', $back_url);
        return $this->fetch("appeal");
    }

    /*
     * 执行添加投诉内容
     * */
    public function doappeal()
    {
        if (request()->isAjax()) {
            $result = array(
                's' => 0,
                'msg' => '投诉提交成功'
            );
            $flag = true;
            $uid = session("user_id");
            $userinfo = userallinfo($uid);
            $info['content'] = cut_not_acccept($_POST['content']);
            //七牛云上传图片
            $info['imgurl'] = $_POST['upload_geturl'];
            if ($flag) {
                $info['ctime'] = time();
                $info['status'] = 1;
                $info['uid'] = $uid;
                $s = Db::name('complain')->insert($info);
                if ($s) {
                    $result['s'] = 1;
                } else {
                    $result['msg'] = "投诉提交失败";
                }
            }
            echo json_encode($result);
            exit();
        }
    }


    /**
     * ATC记录
     */
    public function atcList()
    {
        $uid = session("user_id");
        $userinfo = userallinfo($uid);
        $this->assign('userinfo', $userinfo);
        $set_return = \app\common\model\User::activestatus($userinfo);
        if ($set_return['msg'] != 'ok') {
            session("tips", $set_return["msg"]);
            $this->redirect("User/index");
        }
        /*读取前五条*/
        $list = \db('wages')->where("uid='" . $uid . "'")->order('id desc')->limit(10)->select();
        $this->assign('list', $list);
        return $this->fetch("atc_list");

    }

    /*ajax 加载atc币*/
    public function ajaxmoreatc()
    {
        $page = $_POST['page'];/*当前是第几页*/
        $page_num = 10;/*每次读取10条*/
        $limit_first = ($page - 1) * $page_num;
        $limit_end = $page_num;

        $map['uid'] = session("user_id");
        $list = \db('wages')->where($map)->order('id desc')->limit($limit_first, $limit_end)->select();
        if (!empty($list)) {
            $ary = $list;
            foreach ($ary as $k => $v) {
                $ary[$k]['ctime'] = date('Y-m-d H:i:s', $v['ctime']);
            }
        } else {
            $ary = [];
        }
        echo json_encode($ary);
    }

    /**
     * Atc兑换，现在叫团队奖兑换
     */
    public function atcChange()
    {
        if (request()->isGet()) {
            $this->templateTitle("团队奖兑换");
            $uid = session("user_id");
            $userinfo = userallinfo($uid);
            $this->assign('userinfo', $userinfo);
            return $this->fetch("atc_change");
        } else {
            $uid = session("user_id");
            $userinfo = userallinfo($uid);
            $num = input("num");
            $pwd = input("pwd");
            //校验提交数量是否在有效范围内
            $atc_start = config("setting.atc_start");
            $atc_end = config("setting.atc_end");
            if ($num < $atc_start || $num > $atc_end) {
                $ary = array('s' => 2, 'msg' => '团队奖兑换数量不合法！');
                echo json_encode($ary);
                exit;
            }
            //校验二级密码
            $user = userallinfo(session("user_id"));
            if (encrypt_user_password($pwd) != $user["sepasswd"]) {
                $ary = array('s' => 2, 'msg' => '交易密码错误！');
                echo json_encode($ary);
                exit;
            }
            if ($user["wagesall"] < $num) {
                $ary = array('s' => 2, 'msg' => '可兑换团队奖数量不足！');
                echo json_encode($ary);
                exit;
            }
            $price = round(config("setting.atc_rate") * $num, 2);
            //获取待售商品信息
            $good = \db("goods")->where("price1", "<=", $price)->where("price2", ">=", $price)->where("isshow", 1)->where("isclose", 1)->find();
            if (empty($good)) {
                $ary = array('s' => 2, 'msg' => '该数量额度已售光，请重新填写出售数量！');
                echo json_encode($ary);
                exit;
            }

            //查看共享豆数量是否足够
            if ($good['point_end'] > $userinfo['integral']) {
                $ary = array('s' => 2, 'msg' => '本次出售需要共享豆' . $good['point_end'] . '个，你的共享豆不足！');
                echo json_encode($ary);
                exit;
            }
            //开始执行插入order表的sql语句，就卖给自己好了

            //先把会员共享豆扣了，然后添加新的订单
            \db('user')->where("id='" . $userinfo['id'] . "'")->setDec('integral', $good['point_end']);
            //再把会员的共享豆历史加上
            points_his($userinfo['id'], 2, $good['point_end'], 0, '兑换[团队奖]扣除');
            //先减掉会员团队奖
            \db('User')->where("id='" . $userinfo['id'] . "'")->setDec('wagesall', $num);
            //再添加团队奖收益记录
            wages_his($userinfo['id'], 2, $num, 0, '团队奖兑换');


            $data_sure['buyuid'] = $userinfo['id'];
            $data_sure['buyuidatc'] = $good['atcnum'];
            $data_sure['caifen'] = $good['point_end'];
            $data_sure['productid'] = $good['id'];
            $data_sure['title'] = $good['title'] . '(兑换团队奖)';
            $data_sure['price'] = $price;
            //$data_sure['daynum'] = $good['daynum'];
            $data_sure['daynum'] = 0;
            // $data_sure['earnpercent'] = $good['daypercent'];
            $data_sure['earnpercent'] = 0;
            //一共能赚多少钱，本金加赚的钱有多少
            // $countprofit = countprofit($data_sure['price'], $data_sure['daynum'], $data_sure['earnpercent']);
            // $data_sure['dayaddprice'] = $countprofit['profitall'];
            $data_sure['dayaddprice'] = 0;
            // $data_sure['basicprice'] = $countprofit['profit_and_day'];
            $data_sure['basicprice'] = $price;
            $data_sure['ctime'] = time();
            $data_sure['peiduistatus'] = 1;
            $data_sure['peiduiuid'] = 0;
            $data_sure['peiduitime'] = 0;
            $data_sure['peiduiid'] = 0;
            $data_sure['paystatus'] = 0;
            $data_sure['paytime'] = time();
            $data_sure['payimg'] = '';
            // $cansaletime = ($data_sure['ctime'] + 86400 * $good['daynum']);
            // $cansaletimedate = date('Y-m-d', $cansaletime);
            $now_day_dates = date('Y-m-d');
            $data_sure['thatdatetime'] = strtotime($now_day_dates);
            $data_sure['cansaletime'] = $data_sure['thatdatetime'];

            $data_sure['paytype'] = '';
            $data_sure['xs'] = 2;
            $insertid = db(config('db_order_table'))->insertGetId($data_sure);

            if ($insertid) {
                // for ($i = 1; $i <= $good['daynum']; $i++) {
                //     $data_detail['orderid'] = $insertid;
                //     $data_detail['uid'] = $userinfo['id'];
                //     $data_detail['earnmoney'] = $countprofit['profitday'];
                //     $detail_time = ($data_sure['thatdatetime'] + 86400 * $i);
                //     $data_detail['dotime'] = date('Ymd', $detail_time);
                //     $data_detail['status'] = 1;
                //     $data_detail['ctime'] = time();
                //     \db('orderearn')->insert($data_detail);
                // }
                $ary = array('s' => 10, 'msg' => '兑换成功！');
                echo json_encode($ary);
                exit;
            } else {
                $ary = array('s' => 4, 'msg' => '系统繁忙，请稍后再试！');
                echo json_encode($ary);
                exit;
            }
        }
    }

    /**
     * 加载待出售列表
     */
    public function loadTrade()
    {
        $page = input('page');
        $page_size = input('page_size');
        $list = \db('trade_order')->where('status', 1)->page($page, $page_size)->select();
        $this->ajaxSuccess('请求成功', $list);
    }

    // 服务中心
    public function server_center()
    {
        $trade_info = db('trade_timeline')->where('status', 2)->order('day_time')->limit(7)->select();
        $day_info = empty($trade_info) ? [] : $trade_info[count($trade_info) - 1];
        $this->assign('day_info', $day_info);
        $day_list = [];
        $price_list = [];
        foreach ($trade_info as $item) {
            array_push($day_list, date('m-d', strtotime($item['day_time'])));
            array_push($price_list, $item['day_price']);
        }
        $this->assign('day_list', json_encode($day_list));
        $this->assign('price_list', json_encode($price_list));
        return $this->fetch();
    }

    // 工单提交
    public function work_submit()
    {
        $this->templateTitle("工单提交");
        return $this->fetch();
    }

    // 工单提交2
    public function work_submit_go()
    {
        $this->templateTitle("工单提交");
        $this->assign("type", input("type"));
        return $this->fetch();
    }

    /**
     * 新增工单
     */
    public function addSheet()
    {
        $data = input("post.");
        $data['link_info'] = cut_not_acccept($data['link_info']);
        $data['title'] = cut_not_acccept($data['title1']);
        $data['desc'] = cut_not_acccept($data['desc']);
        unset($data['title1']);
        $data["user_id"] = session("user_id");
        $data["create_time"] = now_datetime();
        \db("work_sheet")->insert($data);
        $this->ajaxSuccess("提交成功");
    }

    // 添加银行卡1
    public function add_bank()
    {
        //判断收款方式设置是否够两种，不够显示提示
        $count = \app\common\model\User::getChargeCount(session("user_id"));
        if ($count >= 2) {
            $this->redirect("paytype/index");
        } else {
            return $this->fetch();
        }
    }

    // 提示过渡
    public function alert_window()
    {
        return $this->fetch();
    }

    /**
     * 确认出售bot
     */
    public function sureSell()
    {
        $user_id = session('user_id');
        $order_id = input('order_id');
        if(empty($order_id)){
            $this->ajaxError('参数错误');
        }
        $order = \db('trade_order')
            ->where('id', $order_id)
            ->where('status', 1)
            ->find();
        if($order['user_id'] == $user_id){
            $this->ajaxError('自己的订单不能交易');
        }
        $user = userallinfo($user_id);
        if($user['mybot']<$order['num']){
            $this->ajaxError('SCB拥有数量不足');
        }
        try {
            \db()->startTrans();
            $log_data = [
                'uid'=>$user_id,
                'isadd'=>2,
                'nums'=>$order['num'],
                'fromuid'=>0,
                'ctime'=>now_datetime(),
                'info'=>'出售SCB,订单id:'.$order_id
            ];
            \db('mybot')->insert($log_data);
            \db('user')->where('id', $user_id)->setDec('mybot', $order['num']);
            \db('trade_order')->where('id', $order_id)->update([
                'status'=>2,
                'sell_user_id'=>$user_id,
                'match_time'=>now_datetime()
            ]);
            \db()->commit();
            $this->ajaxSuccess('操作成功, 等待求购用户付款');
        }catch (\Exception $exception){
            \db()->rollback();
            $this->ajaxError($exception->getMessage());
        }
    }

    //收货地址
    public function address(){
        $this->templateTitle("收货地址");
        $list = Region::userAddressList($this->currentUserId());
        $this->assign("list", $list);
        $this->assign('redirect_url',trim(input('redirect_url')));
        return $this->fetch();
    }

    public function addAddress(){
        if(request()->isAjax()){
            try{
                $name = remove_all_tags2(input('post.name'));
                $mobile = remove_all_tags2(input('post.mobile'));
                $address = remove_all_tags2(input('post.address'));
                $is_def = intval(input('post.is_def'));
                $pro_id = intval(input('post.pro_id'));
                $city_id = intval(input('post.city_id'));
                $area_id = intval(input('post.area_id'));
                $area_position = remove_all_tags2(input('post.area_position'));
                $id = Region::userAddAddress($this->currentUserId(),$name,$mobile,$pro_id,$city_id,$area_id,$address,$is_def,$area_position);
                $this->ajaxSuccess('新增收货地址成功',$id);
            }catch (\Exception $exception){
                global $wechat_has_exception;
                $wechat_has_exception = true;
                $this->ajaxError($exception->getMessage());
            }
        }else{
            $this->templateTitle("新增收货地址");
            $this->assign('redirect_url',trim(input('redirect_url')));
            $region = Region::getCityJson();
            $this->assign('region',json_encode($region));
            return $this->fetch();
        }
    }

    public function editAddress(){
        $id = intval(input('address_id'));
        try{
            if(request()->isAjax()){
                $name = remove_all_tags2(input('post.name'));
                $mobile = remove_all_tags2(input('post.mobile'));
                $address = remove_all_tags2(input('post.address'));
                $is_def = intval(input('post.is_def'));
                $pro_id = intval(input('post.pro_id'));
                $city_id = intval(input('post.city_id'));
                $area_id = intval(input('post.area_id'));
                $area_position = remove_all_tags2(input('post.area_position'));
                $info = Region::userEditAddress($this->currentUserId(),$id,$name,$mobile,$pro_id,$city_id,$area_id,$address,$is_def,$area_position);
                $this->ajaxSuccess($info);
            }else{
                $this->templateTitle("编辑收货地址");
                $this->assign('redirect_url',trim(input('redirect_url')));
                $region = Region::getCityJson();
                $this->assign('region',json_encode($region));
                $info = Region::oneAddress($this->currentUserId(),$id);
                $this->assign('info',$info);

                return $this->fetch();
            }
        }catch (\Exception $exception){
            global $wechat_has_exception;
            $wechat_has_exception = true;
            if(request()->isAjax()){
                $this->ajaxError($exception->getMessage());
            }else{
                $this->showError($exception->getMessage());
            }
        }
    }

    //删除地址
    public function delAddress(){

        if(request()->isAjax()){
            try{
                $id = intval(input('address_id'));
                $info = Region::userRemoveAddress($this->currentUserId(),$id);
                $this->ajaxSuccess($info);
            }catch (\Exception $exception){
                global $wechat_has_exception;
                $wechat_has_exception = true;
                $this->ajaxError($exception->getMessage());
            }
        }
    }

}
